package dao.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * @author huangzhiyang
 * @Date 2023/11/7
 * @Description
 */
public class BaseDaoImpl {

    private static final String DRIVER_NAME =
            "com.mysql.jdbc.Driver";
    private static final String URL =
            "jdbc:mysql://localhost:3306/lib_sys";
    private static final String USER_NAME = "root";
    private static final String PWD = "123456";

    /**
     * 获取数据库连接对象。
     */
    public Connection getConnection() {
        Connection conn;
        // 获取连接并捕获异常
        try {
            Class.forName(DRIVER_NAME);
            conn = DriverManager.getConnection(URL, USER_NAME, PWD);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return conn;
    }

    /**
     * 关闭数据库连接。
     *
     * @param conn 数据库连接
     * @param stmt Statement对象
     * @param rs   结果集
     */
    public void closeAll(Connection conn, Statement stmt,
                         ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        // 若Statement对象不为空，则关闭
        if (stmt != null) {
            try {
                stmt.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        // 若数据库连接对象不为空，则关闭
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
